<template>
  <el-dialog
    v-model="visible"
    class="assign-dialog"
    :title="'床位分配'"
    width="520px"
    :close-on-click-modal="false"
    @closed="onClosed"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="92px" class="assign-form">
      <!-- 病区：只读展示 -->
      <el-form-item label="病区">
        <div class="readonly-text" :title="wardName">{{ ward.wardName || '未知病区' }}</div>
      </el-form-item>
      <!-- 科室：只读展示 -->
      <el-form-item label="科室">
        <div class="readonly-text" :title="deptName">{{ form.deptName || deptName || '未知科室' }}</div>
      </el-form-item>

      <!-- 患者：必填，下拉选择 -->
      <el-form-item label="患者" prop="patientId">
        <el-select v-model="form.patientId" placeholder="请选择患者" filterable style="width: 100%" @change="handlePatientChange">
          <el-option v-for="p in patientOptions" :key="p.patientId" :label="p.patientName" :value="p.patientId" />
        </el-select>
      </el-form-item>

      <!-- 床位：必填，下拉选择 -->
      <el-form-item label="床位" prop="bedId">
        <el-select v-model="form.bedId" placeholder="请选择床位" style="width: 100%">
          <el-option v-for="b in bedOptions" :key="b.bedId" :label="b.bedNo" :value="b.bedId" />
        </el-select>
      </el-form-item>

      <!-- 入院时间：必填，时间选择器；格式：YYYY-MM-DD hh-mm（内部用 HH:mm 存储，提交时转换） -->
      <el-form-item label="入院时间" prop="admissionTime">
        <el-date-picker
          v-model="form.admissionTime"
          type="datetime"
          format="YYYY-MM-DD hh:mm"
          value-format="YYYY-MM-DD hh:mm:ss"
          placeholder="请选择入院时间"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 住院医生：必填，下拉选择，数据源：listUserByPostCode('doctor') -->
      <el-form-item label="住院医生" prop="doctor">
        <el-select v-model="form.doctor" placeholder="请选择住院医生" filterable style="width: 100%">
          <el-option v-for="d in doctorOptions" :key="d.userId" :label="d.nickName" :value="d.userId" />
        </el-select>
      </el-form-item>

      <!-- 住院护士：必填，下拉选择，数据源：listUserByPostCode('nurse') -->
      <el-form-item label="住院护士" prop="nurse">
        <el-select v-model="form.nurse" placeholder="请选择住院护士" filterable style="width: 100%">
          <el-option v-for="n in nurseOptions" :key="n.userId" :label="n.nickName" :value="n.userId" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="assign-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" :loading="saving" @click="onSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="AssignDialog">
import { ref, watch, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import mockBedApi from '@/mock/bed'
import { assignBed } from '@/api/nurseWork/beds.js'
import { listUserByPostCode } from '@/api/system/user'
const { proxy } = getCurrentInstance()

// v-model：控制显示
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  ward: { type: Object, default: () => ({}) },
  deptName: { type: String, default: '' },
  // 可选：默认选中的患者
  defaultPatientId: { type: [Number, String], default: '' },
  // 下拉选项：患者与床位（外部传入，避免重复请求）
  patientOptions: { type: Array, default: () => [] },
  bedOptions: { type: Array, default: () => [] },
  // 可选：默认选中的床位
  defaultBedId: { type: [Number, String], default: '' }
})
const emit = defineEmits(['update:modelValue', 'submitted', 'cancel'])

const visible = ref(false)
const saving = ref(false)
const formRef = ref()
const doctorOptions = ref([])
const nurseOptions = ref([])

// 表单模型
const form = ref({
  admissionId: '',
  patientId: '',
  bedId: '',
  admissionTime: '',
  doctor: ''
})

// 校验规则：所有必填非空
const rules = {
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  bedId: [{ required: true, message: '请选择床位', trigger: 'change' }],
  admissionTime: [{ required: true, message: '请选择入院时间', trigger: 'change' }],
  doctor: [{ required: true, message: '请选择住院医生', trigger: 'change' }],
  nurse: [{ required: true, message: '请选择住院护士', trigger: 'change' }]
}

// 同步 v-model
watch(
  () => props.modelValue,
  v => {
    visible.value = v
    if (v) init()
  }
)
watch(visible, v => emit('update:modelValue', v))
watch(() => props.defaultBedId, v => form.value.bedId = v || '')

// 初始化：默认时间、默认患者、加载医生护士
const init = async () => {
  // 设置默认入院时间为当前时间（格式：YYYY-MM-DD HH:mm）
  const now = new Date()
  const pad = n => String(n).padStart(2, '0')
  const fmt = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(
    now.getMinutes()
  )}`
  form.value.admissionTime = fmt
  form.value.patientId = props.defaultPatientId || ''

  try {
    const [dRes, nRes] = await Promise.all([
      listUserByPostCode('doctor'),
      listUserByPostCode('nurse')
    ])
    if (dRes.code === 200) doctorOptions.value = dRes.rows
    if (nRes.code === 200) nurseOptions.value = nRes.rows
  } catch (e) {
    ElMessage.error('人员列表加载失败')
  }
}

const onSubmit = () => {
  // 提交前进行完整数据校验
  formRef.value?.validate(valid => {
    if (!valid) return
    saving.value = true
    try {
      const payload = {
        id: form.value.admissionId,
        wardId: props.ward.wardId,
        patientId: form.value.patientId,
        hospitalizationNumber: form.value.hospitalizationNumber,
        bedId: form.value.bedId,
        deptId: form.value.deptId,
        admissionTime: form.value.admissionTime,
        residentDoctor: form.value.doctor,
        headNurse: form.value.nurse
      }
      assignBed(payload).then(res => {
        if (res.code === 200) {
          proxy.$modal.notifySuccess('分配成功')
          emit('submitted', payload)
          visible.value = false
        } else {
          proxy.$modal.notifyError(res.msg || '分配失败')
        }
      })
    } finally {
      saving.value = false
    }
  })
}

// 患者选择变化时，更新床位选项
const handlePatientChange = patientId => {
  // 过滤出该患者信息
  const patient = props.patientOptions.find(p => p.patientId === patientId)
  if (patient) {
    form.value.admissionId = patient.admissionId
    form.value.deptId = patient.deptId
    form.value.deptName = patient.deptName
    form.value.hospitalizationNumber = patient.hospitalizationNumber
  }
  if (!props.defaultBedId) form.value.bedId = '' // 清空床位选择
}

const onCancel = () => {
  emit('cancel')
  visible.value = false
}

const onClosed = () => {
  // 重置表单，避免脏数据
  formRef.value?.resetFields()
}

onMounted(() => {
  if (props.modelValue) init()
})
</script>

<style lang="scss" scoped>
.assign-dialog {
  // 统一弹窗样式，保持与 chargingWork 模块一致的简洁风格
  .assign-form {
    .readonly-text {
      color: var(--el-text-color-regular);
      white-space: nowrap; // 只读文本不换行
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .assign-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
